/*
 * @Author: 李超越 1509572300@qq.com
 * @Date: 2024-08-23 09:15:56
 * @LastEditors: 李超越 1509572300@qq.com
 * @LastEditTime: 2024-08-23 15:32:52
 * @FilePath: /my_git/lesson28_thread/thread.hpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <cerrno>
#include <sys/types.h>
#include <vector>
#include <string>
#include <functional>
using namespace std;


namespace ThreadModule
{
    template<typename T>
    using func_t=function<void(T)>;

    template<typename T>
    class Thread
    {
    public:
        Thread(func_t<T> func,T data,const string &name="none-name")
            :_func(func),_data(data),_threadname(name),_stop(true)
        {}

        void Excute()
        {
            _func(_data);
        }

        static void* threadroutine(void* args)
        {
            Thread<T>* self=static_cast<Thread<T>*>(args);
            self->Excute();
            return nullptr;
        }

        bool Start()
        {
            int n=pthread_create(&_tid,nullptr,threadroutine,this);
            if(!n)
            {
                _stop=false;
                return true;
            }
            else
            {
                return false;
            }
        }
        
        void Detach()
        {
            if(!_stop)
            {
                pthread_detach(_tid);
            }
        }

        string name()
        {
            return _threadname;
        }

        void Join()
        {
            if(!_stop)
            {
                pthread_join(_tid,nullptr);
            }
        }

        void Stop()
        {
            _stop=true;
        }

        ~Thread()
        {}
    private:
        pthread_t _tid;
        string _threadname;
        T _data;
        func_t<T> _func;
        bool _stop;
    };
}

class LockGuard
{
public:
    LockGuard(pthread_mutex_t *mutex):_mutex(mutex)
    {
        pthread_mutex_lock(_mutex);
    }

    ~LockGuard()
    {
        pthread_mutex_unlock(_mutex);
    }
private:
    pthread_mutex_t* _mutex;
};